package com.atguigu.eduservice.service.impl;

import com.atguigu.commonutils.ResultInfo;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.mapper.EduVideoMapper;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-01-10
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private VodClient vodClient;

    //1 根据课程id删除小节，删除对应视频文件
    @Override
    public void removeVideoByCourseId(String courseId) {
        //删除视频
        QueryWrapper<EduVideo> wrapperVideo = new QueryWrapper<>();
        wrapperVideo.eq("course_id",courseId);
        wrapperVideo.select("video_source_id");//只显示该字段
        //查询所有小节视频
        List<EduVideo> eduVideoList = baseMapper.selectList(wrapperVideo);
        List<String> videoIdList = new ArrayList<>();
        for (EduVideo eduVideo:eduVideoList) {
            String videoSourceId = eduVideo.getVideoSourceId();
            if (!StringUtils.isEmpty(videoSourceId)){//不为空
                videoIdList.add(videoSourceId);
            }
        }
        //有视频id则删除
        if(eduVideoList.size()>0){
            ResultInfo resultInfo = vodClient.deleteBatch(videoIdList);
            if (resultInfo.getCode()==20001){
                throw new GuliException(20001,"删除视频失败！");
            }
        }

        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        baseMapper.delete(wrapper);
    }
}
